/**
 * 认证服务
 *
 * 处理用户登录、注册、token管理等认证相关功能
 */
import { api } from './api';
import { User, LoginRequest, LoginResponse } from '../types';

export const authService = {
  /**
   * 用户登录
   * @param credentials 登录凭据
   * @returns 登录响应（包含token）
   */
  login: async (credentials: LoginRequest): Promise<LoginResponse> => {
    const response = await api.post<LoginResponse>('/api/auth/login', credentials);

    // 登录成功后保存token到localStorage
    if (response.access_token) {
      localStorage.setItem('access_token', response.access_token);
      localStorage.setItem('token_expires_at',
        String(Date.now() + response.expires_in * 1000)
      );
    }

    return response;
  },

  /**
   * 用户注册
   * @param userData 用户数据
   * @returns 创建的用户信息
   */
  register: async (userData: { username: string; password: string; role?: string }): Promise<User> => {
    return api.post<User>('/api/auth/register', userData);
  },

  /**
   * 获取当前用户信息
   * @returns 当前用户信息
   */
  getCurrentUser: async (): Promise<User> => {
    const user = await api.get<User>('/api/auth/me');

    // 保存用户信息到localStorage
    localStorage.setItem('user_info', JSON.stringify(user));

    return user;
  },

  /**
   * 用户登出
   * 清除本地存储的认证信息
   */
  logout: (): void => {
    localStorage.removeItem('access_token');
    localStorage.removeItem('token_expires_at');
    localStorage.removeItem('user_info');
  },

  /**
   * 检查token是否有效
   * @returns 是否已登录
   */
  isAuthenticated: (): boolean => {
    const token = localStorage.getItem('access_token');
    const expiresAt = localStorage.getItem('token_expires_at');

    if (!token || !expiresAt) {
      return false;
    }

    // 检查token是否过期
    return Date.now() < parseInt(expiresAt);
  },

  /**
   * 获取本地存储的用户信息
   * @returns 用户信息或null
   */
  getStoredUser: (): User | null => {
    const userInfo = localStorage.getItem('user_info');
    return userInfo ? JSON.parse(userInfo) : null;
  },

  /**
   * 获取访问token
   * @returns token或null
   */
  getAccessToken: (): string | null => {
    return localStorage.getItem('access_token');
  },
};